package com.example.customview.head_hover

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2

class HeadScrollerView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defaultStyle: Int = 0
) : NestedScrollView(context, attributeSet, defaultStyle) {
    private val TAG  = "HeadScrollerView"


    override fun onNestedPreScroll(target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) {
        // tablayout_viewpager 的高度和 NestedScrollView 的高度一样，
        // 所以可以用 LinearLayoutCompat的高度 - NestedScrollView的高度，得到 AppCompatImageView
        val headerViewHeight = getChildAt(0).measuredHeight - measuredHeight
        if (dy > 0 /* move up*/ && scrollY < headerViewHeight /* headerview does not hide completely.*/) {
            scrollBy(0, dy)
            consumed[1] = dy
        }
    }
    override fun fling(velocityY: Int) {
        super.fling(velocityY)
        if (velocityY > 0) {
            val viewPager2 = getChildView(this, ViewPager2::class.java)
            if (viewPager2 != null) {
                // In this project configuration, ViewPager2 has only one child RecyclerViewImpl,
                // and RecyclerViewImpl has only one FrameLayout, at last,
                // FrameLayout has only one RecyclerView.
                val childRecyclerView = getChildView(
                    (viewPager2.getChildAt(0) as ViewGroup),
                    RecyclerView::class.java
                )
                childRecyclerView?.fling(0, velocityY)
            }
        }
    }

    private fun <T> getChildView(viewGroup: View?, targetClass: Class<T>): T? {
        if (viewGroup != null && viewGroup.javaClass == targetClass) {
            return viewGroup as T
        }

        if (viewGroup is ViewGroup) {
            for (i in 0 until viewGroup.childCount) {
                val view = viewGroup.getChildAt(i)
                if (view is ViewGroup) {
                    val result = getChildView(view, targetClass)
                    if (result != null) {
                        return result
                    }
                }
            }
        }
        return null
    }


}